<template>
  <div style="height: 100%" ref="echart"></div>
</template>

<script>
import echarts from "echarts";
export default {
  props: {
    chartData: {
      type: Object,
      default() {
        return {
          title: {},

          xData: [], //折线图x轴数据
          series: []
        };
      }
    },
    isAxisChart: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    options() {
      return this.isAxisChart ? this.axisOption : this.pieOption;
    },
    isCollapse() {
      return this.$store.state.tab.isCollapse; //菜单进行折叠时进行图形自适应
    }
  },
  watch: {
    //监听事件
    chartData: {
      handler: function() {
        this.initChart();
      },
      deep: true
    },
    isCollapse() {
      setTimeout(() => {
        this.resizeChart();
      }, 500); //300毫秒就进行一个回调函数，图形进行自适应
    }
  },
  methods: {
    initChart() {
      this.initChartData();
      //取到组件进行初始化
      if (this.echart) {
        this.echart.setOption(this.options);
      } else {
        this.echart = echarts.init(this.$refs.echart);
        this.echart.setOption(this.options);
      }
    },
    initChartData() {
      if (this.isAxisChart) {
        this.axisOption.title = this.chartData.title;
        this.axisOption.xAxis.data = this.chartData.xData;
        this.axisOption.series = this.chartData.series;
      } else {
        this.pieOption.series = this.chartData.series;
      }
    },
    resizeChart() {
      this.echart ? this.echart.resize() : ""; //对折线图的调整
    },
    mounted() {
      window.addEventListener("resize", this.resizeChart); //创建窗口界面自适应
    },
    destroyed() {
      window.removeEventListener("resize", this.resizeChart); //销毁
    }
  },
  data() {
    return {
      echart: null,
      axisOption: {
        title: {},
        legend: {
          textStyle: {
            color: "#333333"
          }
        },
        tooltip: {
          //折线图使用的定位功能
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985"
            }
          }
        },
        xAxis: {
          type: "category",
          data: [],
          axisLine: {
            lineStyle: {
              color: "#17b3a3"
            }
          }
        },
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#17b3a3"
              }
            }
          }
        ],
        series: []
      },
      pieOption: {
        title: { text: "用户占比" },
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {},
        series: []
      }
    };
  }
};
</script>

<style lang="scss" scoped></style>
